﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Kiwi.Container;
using Kiwi.Container.Application;
using Kiwi.Container.DependencyInjection;
using Kiwi.Container.Web;
using Kiwi.Container.Web.Mvc;

namespace SampleMvcApplication
{
    public class MvcApplication : HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Home", action = "Index", id = ""} // Parameter defaults
                );
        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);

            ContainerManager.Configure(CreateContainer, new AspNetFramework());

            MvcContainerApplication.EnableMvcControllerDependencyInjection(Properties.Unset);
            MvcContainerApplication.EnableMvcViewDependencyInjection(Properties.Unset);
        }

        private static IContainer CreateContainer()
        {
            var builder = new ContainerBuilder();

            builder
                .EnablePerHttpSessionContainers()
                .EnablePerHttpRequestContainers()
                .EnableHttpHandlerDependencyInjection(Properties.Unset, true);

            builder.Register(c => HttpContext.Current).Global()
                .NoLifetime()
                .PerHttpRequest();
            builder.Register(c => HttpContext.Current.Request)
                .NoLifetime()
                .PerHttpRequest();
            builder.Register(c => HttpContext.Current.Response)
                .NoLifetime()
                .PerHttpRequest();

            return builder.CreateContainer();
        }
    }
}